<?php
ini_set('memory_limit', '64M');
class SearchAction extends CommonAction {
	public $keywords; 
	private $oldKeyword;
	private $pageUrl = '/search/';
	private $cateObject;
	
	public function __construct(){
		parent::__construct();
		
		$this->modelObject = D('Websites');
		$this->cateObject = D('WebsitesCate');
    }
	
	public function index(){
		$map = array();
		
		$thisPage = I('p', 1);
		$orderBy  = 'id DESC';
		
		//$cateTree = $this->cateObject->getCateTree();
		//$this->assign('cateTree', $cateTree);
		$getKeyword = I('keyword','','strip_tags');
		if(substr_count($_SERVER['REQUEST_URI'], 'search/?')){
			send_http_status(301);
			header('location: '.$this->webConfig['host_url'].'search/'.$getKeyword.'/');
			exit;
		}
		$this->oldKeyword = str_replace(array('+', '  '), ' ', $getKeyword);
		
		if(empty($this->oldKeyword)){
			$this->error('请输入您想查找的网站名称或URL!');	
		}
		
		if(!preg_match('/^.*$/u', $this->oldKeyword)){
			$this->oldKeyword = iconv('GB2312', 'UTF-8', $this->oldKeyword);
		}
		
		$this->keywords = $this->__getKeywords();
		$this->sql      = $this->__getKeywordSql();
		
		//初始值
		$map['_logic']  = 'AND';
		$map['_string'] = $this->sql;
		$map['status'] = 1;
		
		//获得列表
		$list = $this->modelObject->getPageList($map, $thisPage, 0, $orderBy);
		
		$kArr = explode(' ', $this->keywords);
		$kArrRep  = array_map(array($this, 'kArrRep'), $kArr);	
		
		foreach($list as $key=>$val){
			$list[$key]['url']  = setViewUrl('site', $val);	
			$list[$key]['name'] = str_ireplace($kArr, $kArrRep, $val['name']);
		}
					
		$this->assign('list', $list);
		$this->assign('pageUrl', $this->pageUrl.$this->oldKeyword.'/');
		
		//分页
		$page = $this->modelObject->buildPage($map, $thisPage);
		$this->assign('page',$page);
		//p($page);
		
		
		$cateInfo = array();
		$cateInfo['title'] = $this->oldKeyword.'的搜索结果';
		$this->assign('keyword', $this->oldKeyword);
		if($thisPage > 1){
			$cateInfo['title'] .= '第'.$thisPage.'页';
		}
		$this->setSeo($cateInfo);
		$this->assign('cateTree', $this->cateObject->getCateTree());
		$this->display();
    }
	
	/**
	*/
	private function kArrRep($v){
		return "<i>{$v}</i>";
	}
	
	/**
     *  获得关键字的分词结果，并保存到数据库
     *
     * @access    public
     * @param     string  $keyword  关键词
     * @return    string
     */
    private function __getKeywords(){
        // $row = $this->dsql->GetOne("SELECT spwords FROM `#@__search_keywords` WHERE keyword='".addslashes($keyword)."'; ");
		$keyword = $this->oldKeyword;
		$searchKeywords = M('SearchKeywords');
		$spwords = $searchKeywords->where("keyword = '%s'", $keyword)->getField('spwords');
		if(empty($spwords)){
            if(strlen($keyword)>7){
                //初始化类
				import('ORG.Net.SplitWord');
				$pa = new SplitWord('utf-8', 'utf-8'); ///初始化对象
				$pa->SetSource($keyword);
				$pa->SetResultType(2);
				$pa->StartAnalysis(TRUE); //执行分词
				$keywords = $pa->GetFinallyResult(' '); //输出分词结果
				
				$keywords = preg_replace("/[ ]{1,}/", " ", trim($keywords));
            }else{
                $keywords = $keyword;
            }
			
			$data 			     = array();
			$data['keyword']     = $keyword;
			$data['spwords']     = $keywords;
			$data['update_time'] = NOW_TIME;
			
			$searchKeywords->add($data);
        }else{
			$data 			     = array();
			$data['count']       = array('exp', 'count+1');
			$data['update_time'] = NOW_TIME;
			$searchKeywords->where("keyword = '%s'", $keyword)->save($data);
            $keywords = $spwords;
        }
        return $keywords;
    }
	
	/**
     *  获得关键字SQL
     *
     * @access    private
     * @return    string
     */
    private function __getKeywordSql(){
        $ks = explode(' ',$this->keywords);
        $kwsql = '';
        $kwsqls = array();
		if(count($ks) > 1){
        foreach($ks as $k){
            $k = trim($k);
            if(strlen($k)<1){
                continue;
            }
            if(ord($k[0])>0x80 && strlen($k)<2){
                continue;
            }
            $k = addslashes($k);
			
			$kwsqls[] = " name LIKE '%$k%' OR domain LIKE '%$k%' "; //" CONCAT(name,' ',keywords) LIKE '%$k%' ";
        }
		}
		 $kwsqls[] = " name LIKE '%{$this->oldKeyword}%' OR domain LIKE '%{$this->oldKeyword}%' ";
		
        if(!isset($kwsqls[0])){
            return '';
        }else{
            $kwsql = implode(' OR ',$kwsqls);
            return $kwsql;
        }
    }
		
	
}//end class